package com.example.casper.Experiment2024;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import android.view.ContextMenu;

import com.example.casper.Experiment2024.data.book;

import java.util.List;

public class RecyclerViewBookAdapter extends RecyclerView.Adapter<RecyclerViewBookAdapter.BookViewHolder> {

    private final Context context;
    private final List<book> bookList;
    private final int clickedPosition = -1; // 保存点击位置

    public RecyclerViewBookAdapter(Context context, List<book> bookList) {
        this.context = context;
        this.bookList = bookList;
    }

    @NonNull
    @Override
    public BookViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.book_item, parent, false);
        return new BookViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull BookViewHolder holder, int position) {
        book book = bookList.get(position);
        holder.imageViewBookCover.setImageResource(book.getCoverResourceId());
        holder.textViewBookName.setText(book.getTitle());
        holder.textViewBookPrice.setText(book.getPrice());
    }

    @Override
    public int getItemCount() {
        return bookList.size();
    }

    public static class BookViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
        public ImageView imageViewBookCover;
        public TextView textViewBookName;
        public TextView textViewBookPrice;

        public BookViewHolder(@NonNull View itemView) {
            super(itemView);
            imageViewBookCover = itemView.findViewById(R.id.image_view_book_cover);
            textViewBookName = itemView.findViewById(R.id.text_view_book_name);
            textViewBookPrice = itemView.findViewById(R.id.text_view_book_price);

            itemView.setOnCreateContextMenuListener(this);
        }

        @Override
        public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
            menu.setHeaderTitle("具体操作");

            menu.add(0, 0, this.getAdapterPosition(), "添加" + this.getAdapterPosition());
            menu.add(0, 1, this.getAdapterPosition(), "删除" + this.getAdapterPosition());
            menu.add(0, 2, this.getAdapterPosition(), "修改" + this.getAdapterPosition());
        }
    }
}
